/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package controllers;

import hibentities.Producer;
import hibernatedaos.ProducerHibernateDao;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

/**
 * @author piotrek
 */
@Controller
@RequestMapping(value="/hibernate")
public class ProducerHibernateController {

	private final ProducerHibernateDao producerDao;
	
	@Autowired
    public ProducerHibernateController( ProducerHibernateDao producerDao) {
		this.producerDao = producerDao;
	}

	@RequestMapping(value="/producer/list")
    protected String showProducerListHibernate(Model model) throws Exception {

		List<Producer> producerList = producerDao.getProducerList();

		model.addAttribute( "producerList", producerList );

		model.addAttribute( "requestType", "hibernate" );

		return "producerList";

	}

	@RequestMapping(value="/{id}/producer", method=RequestMethod.GET)
    protected String showProducerHibernate( @PathVariable("id") String id,
            Model model) throws Exception {

		model.addAttribute( "id", id );

		Producer producer = producerDao.getProducer( Long.parseLong(id) );

		model.addAttribute( "user", producer );

		return "producer";
    }

	@RequestMapping(value="/{id}/producer/update")
    protected String updateProducerHibernate( @PathVariable("id") String id,
            Model model) throws Exception {

		Producer producer = producerDao.getProducer( Long.parseLong(id) );

		producer.setName("qwerty");

		producerDao.updateProducer(producer);

		return "success";
    }


	@RequestMapping(value="/{id}/producer/delete", method=RequestMethod.GET)
    protected String deleteProducerHibernate( @PathVariable("id") String id,
            Model model) throws Exception {

		producerDao.deleteProducer( Long.parseLong(id) );

		return "success";
	}

	@RequestMapping(value="/producer/add")
	protected String saveProducer( HttpServletRequest request,
            HttpServletResponse response){

		Producer p = new Producer();
		p.setName( (String)request.getParameter("name") );
		p.setDescription( (String)request.getParameter("description") );

		producerDao.addProducer( p );

		return "success";

	}

}
